package com.torry.workflow.common.filter;

import com.alibaba.fastjson.JSON;

import com.torry.workflow.common.base.result.Result;
import com.torry.workflow.common.exception.BizException;
import com.torry.workflow.common.util.HttpContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;


@Component
@Slf4j
public class JwtFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    private List<String> uriPrefixWhiteList = Arrays.asList(
            "/login",
            "/file",
            "/user/login",
            "/admin/interviewer/list",
            "/admin/jobtitle/list",
            "/admin/jobtitle/pids"

    );

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        //log.info("【JwtFilter】 url: {}", uri);

        filterChain.doFilter(servletRequest, servletResponse);

       /* // 白名单
        if (uriPrefixWhiteList.contains(uri)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // TOKEN为空
        String token = request.getHeader(AuthConstant.TOKEN_NAME);
        if (StringUtils.isEmpty(token) || token.equals("undefined")) {
            responseJSON(new AuthException(AuthExceptionEnum.TOKEN_IS_EMPTY));
            return;
        }

        // TOKEN过期
        try {
            if (JwtUtil.isTokenExpired(token)) {
                responseJSON(new AuthException(AuthExceptionEnum.TOKEN_INVALID));
                return;
            }
        } catch (Exception e) {
            // 非法TOKEN
            responseJSON(new AuthException(AuthExceptionEnum.ILLEGAL_REQUEST));
            return;
        }

        // 正常放行
        filterChain.doFilter(servletRequest, servletResponse);*/

    }

    @Override
    public void destroy() {

    }

    private void responseJSON(BizException ex) throws IOException {
        HttpServletResponse response = HttpContextUtil.getResponse();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        Result result = Result.fail(ex.getCode(), ex.getMsg());

        response.getWriter().write(JSON.toJSONString(result));

    }
}
